package com.xishu.service;

import com.xishu.config.Config;
import com.xishu.exception.ResponseStatusException;
import com.xishu.util.FileUtil;
import com.xishu.util.MongoId;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import software.amazon.awssdk.core.sync.RequestBody;
import software.amazon.awssdk.regions.Region;
import software.amazon.awssdk.services.s3.S3Client;
import software.amazon.awssdk.services.s3.model.GetObjectRequest;
import software.amazon.awssdk.services.s3.model.PutObjectRequest;

import java.io.File;
import java.nio.file.FileSystems;
import java.nio.file.Path;

/**
 * 亚马逊对象存储
 */
public class S3Service {
    private static Logger logger = LoggerFactory.getLogger(S3Service.class);
    private static S3Service instance = new S3Service();
    private S3Client s3;

    public static S3Service getInstance() {
        return instance;
    }

    private S3Service() {
        if (Config.getInstance().isUsVersion()) {
            s3 = S3Client.builder()
                    .region(Region.US_WEST_1)
                    .build();
        } else {
            s3 = S3Client.builder()
                    .region(Region.AP_EAST_1)
                    .build();
        }


    }

    /**
     * 上传文件到桶
     *
     * @param srcFile
     */
    public void uploadObject(File srcFile) {
        Config config = Config.getInstance();
        uploadObject(config.getS3BucketName(), srcFile.getName(), srcFile);
    }

    /**
     * 上传文件
     *
     * @param bucketName
     * @param objectName
     * @param srcFile
     */
    public void uploadObject(String bucketName, String objectName, File srcFile) {
        logger.info("will upload file {} to bucket {} object {}", srcFile.getAbsolutePath(), bucketName, objectName);


        PutObjectRequest objectRequest = PutObjectRequest.builder()
                .bucket(bucketName)
                .key(objectName)
                .contentType("application/octet-stream")
                .build();

        s3.putObject(objectRequest, RequestBody.fromFile(srcFile));
    }

    /**
     * 下载文件
     *
     * @param bucketName
     * @param objectName
     */
    public File downloadFile(String bucketName, String objectName) throws ResponseStatusException {
        GetObjectRequest getObjectRequest = GetObjectRequest.builder()
                .bucket(bucketName)
                .key(objectName)
                .build();

        File file = MongoId.getInstance().generateTmpFile(FileUtil.getSuffix(objectName));
        Path path = FileSystems.getDefault().getPath(file.getAbsolutePath());
        s3.getObject(getObjectRequest, path);
        return file;
    }

}
